package com.example.filter;
//手动解决跨域的过滤器

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.example.utils.Const.ORDER_CORS;


@Component
//提高自定义过滤器的优先级
@Order(ORDER_CORS)
public class CorsFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //添加跨域信息
        this.addCorsHeader(request,response);
        //放行
        chain.doFilter(request,response);
    }

    //添加cors header
    private void addCorsHeader(HttpServletRequest request, HttpServletResponse response){
        //允许访问的原始站点origin访问
        response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response.addHeader("Access-Control-Allow-Headers", "Authorization,Content-type");
    }
}
